package com.snap.awesomeserial.model;

import com.snap.awesomeserial.bean.TemplateEntity;

import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;
import org.litepal.crud.callback.SaveCallback;
import org.litepal.crud.callback.UpdateOrDeleteCallback;
import org.litepal.tablemanager.Connector;

class DBModel {

    DBModel() {
        Connector.getDatabase();
    }

    //=============================👇模板👇==================================
    //保存模板
    void saveDemo(TemplateEntity demo, SaveCallback callback) {
        demo.saveOrUpdateAsync("name = ?", demo.getName())
                .listen(callback);
    }

    //获取模板列表
    void getDemoList(int limit, FindMultiCallback<TemplateEntity> callback) {
        LitePal.order("createTime desc")
                .limit(limit)
                .findAsync(TemplateEntity.class)
                .listen(callback);
    }

    //删除模板（单个，多个）
    void deleteDemo(UpdateOrDeleteCallback callback, String... demoID) {
        if (demoID.length == 0) {
            callback.onFinish(0);
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("'").append(demoID[0]).append("'");
        for (int i = 1; i < demoID.length; i++) {
            sb.append(",").append("'").append(demoID[i]).append("'");
        }
        String whereClause = String.format("name in (%s)", sb.toString());
        LitePal.deleteAllAsync(TemplateEntity.class, whereClause)
                .listen(callback);
    }
}
